const { app, BrowserWindow, ipcMain, Menu, dialog } = require('electron')
const path = require('path')
const Database = require('./src/database/db')
const AIService = require('./src/utils/aiService')

class ConsumptionApp {
  constructor() {
    this.mainWindow = null
    this.database = new Database()
    this.aiService = new AIService()
  }

  createWindow() {
    this.mainWindow = new BrowserWindow({
      width: 1200,
      height: 800,
      minWidth: 800,
      minHeight: 600,
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js')
      },
      icon: path.join(__dirname, 'assets/icon.png'),
      titleBarStyle: 'default',
      show: false
    })

    this.mainWindow.loadFile('src/renderer/index.html')

    // 窗口准备好后显示
    this.mainWindow.once('ready-to-show', () => {
      this.mainWindow.show()
    })

    // 监听渲染进程的控制台输出
    this.mainWindow.webContents.on('console-message', (event, level, message, line, sourceId) => {
      console.log(`[Renderer] ${message}`)
    })

    // 开发环境下打开开发者工具
    if (process.env.NODE_ENV === 'development' || process.argv.includes('--dev')) {
      this.mainWindow.webContents.openDevTools()
    }

    this.mainWindow.on('closed', () => {
      this.mainWindow = null
    })
  }

  createMenu() {
    const template = [
      {
        label: '文件',
        submenu: [
          {
            label: '新建记录',
            accelerator: 'CmdOrCtrl+N',
            click: () => {
              this.mainWindow.webContents.send('menu-new-record')
            }
          },
          {
            label: '导入数据',
            click: async () => {
              const result = await dialog.showOpenDialog(this.mainWindow, {
                properties: ['openFile'],
                filters: [{ name: 'CSV Files', extensions: ['csv'] }]
              })
              if (!result.canceled) {
                this.mainWindow.webContents.send('menu-import-data', result.filePaths[0])
              }
            }
          },
          {
            label: '导出数据',
            click: async () => {
              const result = await dialog.showSaveDialog(this.mainWindow, {
                filters: [{ name: 'CSV Files', extensions: ['csv'] }]
              })
              if (!result.canceled) {
                this.mainWindow.webContents.send('menu-export-data', result.filePath)
              }
            }
          },
          { type: 'separator' },
          {
            label: '退出',
            accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
            click: () => {
              app.quit()
            }
          }
        ]
      },
      {
        label: '视图',
        submenu: [
          {
            label: '刷新',
            accelerator: 'CmdOrCtrl+R',
            click: () => {
              this.mainWindow.webContents.reload()
            }
          },
          {
            label: '开发者工具',
            accelerator: 'F12',
            click: () => {
              this.mainWindow.webContents.toggleDevTools()
            }
          }
        ]
      },
      {
        label: '帮助',
        submenu: [
          {
            label: '关于',
            click: () => {
              dialog.showMessageBox(this.mainWindow, {
                type: 'info',
                title: '关于',
                message: '消费记录工具',
                detail: '智能消费记录和分析工具\n版本: 1.0.0'
              })
            }
          }
        ]
      }
    ]

    const menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
  }

  setupIPC() {
    // 数据库操作
    ipcMain.handle('db-get-expenses', async (event, filters) => {
      return await this.database.getExpenses(filters)
    })

    ipcMain.handle('db-add-expense', async (event, expense) => {
      return await this.database.addExpense(expense)
    })

    ipcMain.handle('db-update-expense', async (event, id, expense) => {
      return await this.database.updateExpense(id, expense)
    })

    ipcMain.handle('db-delete-expense', async (event, id) => {
      return await this.database.deleteExpense(id)
    })

    ipcMain.handle('db-get-categories', async () => {
      return await this.database.getCategories()
    })

    ipcMain.handle('db-add-category', async (event, category) => {
      return await this.database.addCategory(category)
    })

    ipcMain.handle('db-get-statistics', async (event, period) => {
      return await this.database.getStatistics(period)
    })

    // 智能服务
    ipcMain.handle('ai-analyze-expenses', async (event, expenses) => {
      return await this.aiService.analyzeExpenses(expenses)
    })

    ipcMain.handle('ai-suggest-category', async (event, description) => {
      return await this.aiService.suggestCategory(description)
    })

    ipcMain.handle('ai-generate-report', async (event, data) => {
      return await this.aiService.generateReport(data)
    })
  }

  async initialize() {
    await this.database.initialize()
    this.setupIPC()
    this.createMenu()
    this.createWindow()
  }
}

const consumptionApp = new ConsumptionApp()

app.whenReady().then(() => {
  consumptionApp.initialize()
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    consumptionApp.createWindow()
  }
})